"""
项目：Ai-Engineer自适应工程设计自动化插件
作者：刘昊轩、李佳音、刘伟伟、杨明久（排序不分先后）
©版权保护
"""
import json
import re
from jsonschema import validate
from json import JSONDecodeError
import ast
import logging
import jsoncomment


class CommandParser:

    def __init__(self):
        self.logger = logging.getLogger("CommandParser")
        self.parser = jsoncomment.JsonComment(json)

    @staticmethod
    def preprocess_response(response: str) -> str:
        """清理响应中的非JSON内容"""
        # 移除所有注释块
        response = re.sub(r'<think>.*?</think>', '', response, flags=re.DOTALL)

        # 替换中文标点
        replacements = {"，": ",", "：": ":", "；": ";"}
        for cn, en in replacements.items():
            response = response.replace(cn, en)

        # 提取第一个完整JSON对象
        start = response.find('{')
        end = response.rfind('}') + 1
        return response[start:end] if start != -1 else ""

    # 修改后的SCHEMA，支持rectangle类型
    SCHEMA = {
        "type": "object",
        "properties": {
            # 命令类型，可取值为 draw（绘制）、modify（修改）、analyze（分析）
            "command_type": {"enum": ["draw", "modify", "analyze"]},
            # 具体的 CAD 命令，为字符串类型
            "command": {"type": "string"},
            "entities": {
                "type": "array",
                "items": {
                    "oneOf": [
                        {
                            "type": "object",
                            "properties": {
                                # 实体类型为矩形
                                "type": {
                                    "type": "string",
                                    "enum": ["rectangle"]
                                },
                                # 矩形的起始点坐标，为包含两个数字的数组
                                "start": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2},
                                # 矩形的宽度，为非负数字
                                "width": {"type": "number", "minimum": 0},
                                # 矩形的高度，为非负数字
                                "height": {"type": "number", "minimum": 0},
                                # 矩形所在的图层，为字符串类型
                                "layer": {"type": "string"},
                                # 矩形使用的材料，为字符串类型
                                "material": {"type": "string"},
                                "dimensions": {
                                    "type": "object",
                                    "properties": {
                                        # 矩形的长度，为非负数字
                                        "length": {"type": "number", "minimum": 0},
                                        # 矩形的宽度，为非负数字
                                        "width": {"type": "number", "minimum": 0},
                                        # 长度的公差，为字符串类型
                                        "tolerance_length": {"type": "string"},
                                        # 宽度的公差，为字符串类型
                                        "tolerance_width": {"type": "string"},
                                        # 角度的公差，为字符串类型
                                        "angle_tolerance": {"type": "string"}
                                    },
                                    "required": ["length", "width", "tolerance_length", "tolerance_width",
                                                 "angle_tolerance"]
                                }
                            },
                            "required": ["type", "start", "width", "height", "layer", "dimensions"]
                        },
                        {
                            "type": "object",
                            "properties": {
                                # 实体类型为圆形
                                "type": {
                                    "type": "string",
                                    "enum": ["circle"]
                                },
                                # 圆形的圆心坐标，为包含两个数字的数组
                                "center": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2},
                                # 圆形的半径，为非负数字
                                "radius": {"type": "number", "minimum": 0},
                                # 圆形所在的图层，为字符串类型
                                "layer": {"type": "string"},
                                # 圆形使用的材料，为字符串类型
                                "material": {"type": "string"}
                            },
                            "required": ["type", "center", "radius", "layer"]
                        }
                    ]
                }
            },
            # 符合的标准列表，为字符串数组
            "compliance": {"type": "array", "items": {"type": "string"}}
        },
        "required": ["command_type", "entities"]
    }

    def _validate_command(self, command: dict, SCHEMA=SCHEMA):
        try:
            validate(instance=command, schema=SCHEMA)
        except Exception as e:
            raise ValueError(f"命令结构验证失败: {str(e)}")

    def _parse_command(self, response: str) -> dict:
        """增强的 JSON 解析方法"""
        try:
            # 预处理响应内容
            cleaned_response = response.strip()

            # 尝试标准 JSON 解析
            try:
                return json.loads(cleaned_response)
            except JSONDecodeError as e:
                # 尝试处理单引号问题
                cleaned_response = cleaned_response.replace("'", '"')

                # 尝试宽松解析
                try:
                    return json.loads(cleaned_response, strict=False)
                except:
                    # 最终尝试使用 ast 解析
                    return ast.literal_eval(cleaned_response)

        except Exception as e:
            logger = logging.getLogger("command")
            logger.error("解析失败的原始响应：%s", response)
            raise ValueError(f"命令解析失败：{str(e)}") from e